//
//  BeautyDownloadManager.swift
//  TestModelActor
//
//  Created by rolodestar on 2025/6/18.
//

import Foundation

class BeautyDownloadManager: NSObject{
    var actor: BeautyModelActor
    var model: BeautyModel
    var session: URLSession
    var downloadTask: URLSessionDownloadTask?
    init(actor: BeautyModelActor, model: BeautyModel) {
        self.actor = actor
        self.model = model
        session = URLSession.shared
        downloadTask = nil
        super.init()
        let config = URLSessionConfiguration.default// .background(withIdentifier: "rolodestar.BeautyDownloadManager.session")
        let backgroundQueue = OperationQueue()
        backgroundQueue.qualityOfService = .background
        session = URLSession(configuration: config, delegate: self, delegateQueue:  backgroundQueue)
        let urlRequest = URLRequest(url: model.remoteUrl)
        downloadTask =  session.downloadTask(with: urlRequest)
        downloadTask?.delegate = self
    }
    
    func startDownload() async{
        Task.detached {
            switch self.model.status{
            case .notStart:
                self.downloadTask?.resume()
            case .pause( _):
                await self.resumeDownload()
            default:
                return
            }
        }
    }
    func reStartDownload() async{
        Task.detached {
          
                self.downloadTask?.resume()
            
        }
    }
    func pauseDownload() async{
        Task.detached {
            let data = await self.downloadTask?.cancelByProducingResumeData()
            await self.actor.update(model: self.model, by: .pause(resumeData: data))
        }
    }
    func resumeDownload() async{
        var data: Data
        switch model.status{
        case .pause(let resumeData):
            if resumeData != nil{
                data = resumeData!
            }else{
                return
            }
        default:
            return
        }
        self.downloadTask = session.downloadTask(withResumeData: data)
        downloadTask?.delegate = self
        downloadTask?.resume()
    }
    
}

extension BeautyDownloadManager: URLSessionDownloadDelegate{
    func createLocalUrl(by downloadTask: URLSessionDownloadTask) -> URL{
        guard let response = downloadTask.response else{ return URL(fileURLWithPath: "/").appending(path: "\(model.id.uuidString).mp4", directoryHint: .notDirectory) }
        let fileName = response.suggestedFilename == nil ? "\(model.id.uuidString).mp4" : response.suggestedFilename!
        do{
            if let folder = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
            {
                let filePath = folder.appending(path: "RoDownload", directoryHint: .isDirectory)
                try FileManager.default.createDirectory(at: filePath, withIntermediateDirectories: true)
                return filePath.appending(path: fileName, directoryHint: .notDirectory)
            }else{
                return URL(fileURLWithPath: "/")
            }
        }catch{
            return URL(fileURLWithPath: "/")
        
        }
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        let localUrl = createLocalUrl(by: downloadTask)
        do{
            try FileManager.default.moveItem(at: location, to: localUrl)
        }catch{
            print(error)
            return
        }
        Task{
            await actor.update(model: model, by: localUrl)
        }
    }
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
        Task{
            await actor.update(model: model, by: .downloading(progress: progress))
        }
    }
    
    
}
